<template>
  <a-spin :spinning="loading">
    <!-- 列表组件 -->
    <Table ref="formRef" />
  </a-spin>
</template>

<script lang="ts" setup>
  import { watch, computed, ref, unref, onMounted } from 'vue';
  import { orgCategoryOptions } from '../data';
  import Table, { Exposed }  from './Table.vue'

  const emit = defineEmits(['success']);
  const props = defineProps({
    data: { type: Object, default: () => ({}) },
    rootTreeData: { type: Array, default: () => [] },
  });
  const loading = ref<boolean>(false);
  // 当前的弹窗数据
  const model = ref<object>({});

  const categoryOptions = computed(() => {
    if (!!props?.data?.parentId) {
      return orgCategoryOptions.child;
    } else {
      return orgCategoryOptions.root;
    }
  });
  

  onMounted(() => {
    // data 变化，重填表单
    watch(
      () => props.data,
      async () => {
        let record = unref(props.data);
        if (typeof record !== 'object') {
          record = {};
        }
        model.value = record;
        onReset({...record})
      },
      { deep: true, immediate: true }
    );
    // 更新 父部门 选项
    watch(
      () => props.rootTreeData,
      async () => {
        if (formRef.value) {
          await formRef.value.updateTreeData(props.rootTreeData)
        }
      },
      { deep: true, immediate: true }
    );
    // 监听并更改 orgCategory options
    watch(
      categoryOptions,
      async () => {
        if (formRef.value) {
          await formRef.value.updateCategoryOptions(categoryOptions.value)
        }
      },
      { immediate: true }
    );
  });

  const formRef = ref<Exposed | null>(null)

  // 重置表单
  async function onReset(data) {
    if (formRef.value) {
      await formRef.value.resetForm(data)
    }
  }

</script>

<style lang="less" scoped>
</style>
